package com.gx.smart.building.ui.swap.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.AsyncTask
import android.provider.MediaStore
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.gx.smart.base.BaseMVVMFragmentV2
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentMySwapWorkBinding
import com.gx.smart.building.ui.common.adapter.ImageAdapter
import com.gx.smart.building.ui.swap.SignatureActivity
import com.gx.smart.building.ui.swap.SwapResultActivity
import com.gx.smart.building.ui.swap.adapter.SwapDeviceConfirmResultAdapter
import com.gx.smart.building.ui.swap.adapter.SwapDeviceResultAdapter
import com.gx.smart.building.ui.swap.adapter.SwapDeviceStatusResultAdapter
import com.gx.smart.building.ui.swap.adapter.SwapRepairAdapter
import com.gx.smart.building.ui.swap.adapter.SwapWarningAdapter
import com.gx.smart.building.ui.swap.viewmodel.MySwapWorkViewModel
import com.gx.smart.lib_http.BuildConfig
import com.huishi.gx.ib.grpc.lib.ib.admin.schedule.v1.RecordDto
import com.mylhyl.circledialog.CircleDialog
import com.orhanobut.logger.Logger
import java.util.Calendar

class MySwapWorkFragment : BaseMVVMFragmentV2<MySwapWorkViewModel>() {
    private lateinit var viewBinding: FragmentMySwapWorkBinding
    private lateinit var stateAdapter: SwapDeviceResultAdapter
    private lateinit var recordAdapter: SwapDeviceStatusResultAdapter
    private lateinit var eventAdapter: SwapDeviceConfirmResultAdapter
    private lateinit var workOrderAdapter: SwapRepairAdapter
    private lateinit var alarmAdapter: SwapWarningAdapter
    private lateinit var imageAdapter: ImageAdapter
    private lateinit var item: RecordDto
    private var addContent: RecordDto.Builder = RecordDto.newBuilder()
    private var state = 1//1：未签字 2：已经签字
    override fun onBindLayout(): Int = R.layout.fragment_my_swap_work

    override fun getToolbarTitle(): String = "交接班"

    override fun onBindViewModel(): Class<MySwapWorkViewModel> = MySwapWorkViewModel::class.java


    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentMySwapWorkBinding.inflate(layoutInflater, root, true)
        stateAdapter = SwapDeviceResultAdapter(requireContext())
        viewBinding.deviceRecyclerView.adapter = stateAdapter
        recordAdapter = SwapDeviceStatusResultAdapter(requireContext())
        viewBinding.deviceStatusRecyclerView.adapter = recordAdapter
        eventAdapter = SwapDeviceConfirmResultAdapter(requireContext())
        viewBinding.deviceConfirmRecyclerView.adapter = eventAdapter
        workOrderAdapter = SwapRepairAdapter(requireContext())
        viewBinding.workOrderRecyclerView.adapter = workOrderAdapter
        alarmAdapter = SwapWarningAdapter(requireContext())
        viewBinding.alarmRecyclerView.adapter = alarmAdapter
        imageAdapter = ImageAdapter(requireContext())
        viewBinding.imageRecyclerView.adapter = imageAdapter

        viewBinding.signature.setOnClickListener {
            //1：未签字 2：已经签字
            if (state == 1) {
                signature()
            } else {
                val currentTime = Calendar.getInstance().timeInMillis
                if (currentTime < item.floatTimeBegin || currentTime > item.floatTimeEnd) {
                    CircleDialog.Builder()
                        .setTitle("不可签收")
                        .setText("不在交接时间内，不可签收")
                        .setPositive("确定", null)
                        .show(requireActivity().supportFragmentManager)
                    return@setOnClickListener
                }
                //签收
                signIn()
            }

        }

    }

    private fun signIn() {
        viewModel.checkAppScheduleRecord(addContent.build())
            .observe(viewLifecycleOwner) {
                if (it) {
                    startActivity(Intent(requireActivity(), SwapResultActivity::class.java))
                    requireActivity().finish()
                }
            }
    }

    override fun initData() {
        super.initData()
        val id = requireActivity().intent.getStringExtra("id")!!
        viewModel.queryAppScheduleRecordDetail(id)
            .observe(viewLifecycleOwner) {
                item = it
                bindUI(it)
                addContent = RecordDto.newBuilder(it)
            }
    }

    private fun bindUI(item: RecordDto) {
        //App专用 1我的交班 2我的接班
        if (item.recordType == 1) {
            viewBinding.title.text = "我的交班"
            viewBinding.type.text = "接班人"
            viewBinding.shiftPerson.text = item.overPerson
        } else {
            viewBinding.title.text = "我的接班"
            viewBinding.type.text = "交班人"
            //交班人
            viewBinding.shiftPerson.text = item.shiftPerson
        }
        //交接单状态 1未签收 2已签收 预留（3提前签收 4超时签收）
        if (item.status == 2) {
            viewBinding.submitLayout.visibility = View.GONE
            viewBinding.signatureLayout.visibility = View.VISIBLE
            //签名
            Glide.with(this).load(BuildConfig.FILE_UPLOAD_URL + item.nameFile)
                .into(viewBinding.signatureImage)
            viewBinding.status.text = "已完成"
            viewBinding.status.setTextColor(resources.getColor(R.color.font_color_style_24))
            viewBinding.status.setBackgroundResource(R.drawable.shape_status_green_text_view_background)
        } else {
            viewBinding.submitLayout.visibility = View.VISIBLE
            viewBinding.signatureLayout.visibility = View.GONE
            viewBinding.status.text = "未签收"
            viewBinding.status.setTextColor(resources.getColor(R.color.font_color_style_eleven))
            viewBinding.status.setBackgroundResource(R.drawable.shape_status_text_view_background)
        }

        viewBinding.organName.text = item.organName
        viewBinding.scheduleName.text = item.scheduleName
        //2022-08-19 11:30-12:00
        val begin = TimeUtils.millis2String(item.floatTimeBegin, "yyyy-MM-dd HH:mm")
        val end = TimeUtils.millis2String(item.floatTimeEnd, "HH:mm")
        viewBinding.floatTimeBeginEnd.text = "$begin-$end"
        //交接内容
        stateAdapter.addAll(item.stateList)
        recordAdapter.addAll(item.recordList)
        eventAdapter.addAll(item.eventList)
        //提醒事项
        viewBinding.remind.text = item.remind ?: ""
        //关联事项
        if (item.workOrderContentCount == 0) {
            viewBinding.workOrderLabel.text = "维修工单：无"
        } else {
            workOrderAdapter.addAll(item.workOrderContentList)
        }
        if (item.alarmContentCount == 0) {
            viewBinding.alarmLabel.text = "报警记录：无"
        } else {
            alarmAdapter.addAll(item.alarmContentList)
        }

        //图片上传
        imageAdapter.addAll(item.fileList.map { BuildConfig.FILE_UPLOAD_URL + it.fileUrl })

    }

    private val signatureRequest = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            if (data != null) {
                val uri = data.getParcelableExtra<Uri>("uri")
                state = 2
                viewBinding.signatureLayout.visibility = View.VISIBLE
                viewBinding.signature.text = "签收"
                //签名
                Glide.with(this).load(uri).into(viewBinding.signatureImage)
                showInitLoadView(true)
                UploadImageAsyncTask().execute(uri)
                viewModel.uploadSuccess.observe(viewLifecycleOwner) {
                    showInitLoadView(false)
                    addContent.nameFile = it.path
                }
                viewModel.error.observe(viewLifecycleOwner) {
                    showInitLoadView(false)
                }
            }
        }
    }

    private fun signature() {
        val id = requireActivity().intent.getStringExtra("id")!!
        val intent = Intent(requireActivity(), SignatureActivity::class.java)
        intent.putExtra("id", id)
        signatureRequest.launch(intent)
    }


    // 通过uri加载图片
    private fun getBitmapFromUri(uri: Uri): Bitmap? {
        try {
            val parcelFileDescriptor = activity!!.contentResolver.openFileDescriptor(uri, "r")
            val fileDescriptor = parcelFileDescriptor!!.fileDescriptor
            val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
            parcelFileDescriptor.close()
            return image
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun uploadImage1(uri: Uri) {
        val fileName = getFileNameByUri(uri)
        Logger.d("uploadImage fileName=$fileName")
        val bitmap = getBitmapFromUri(uri)
        Logger.d("uploadImage bitmap : $bitmap" != null)
        val newBitmap = ImageUtils.compressBySampleSize(bitmap, 500, 500)
        Logger.d("newBitmap size:" + newBitmap.byteCount)
        val file = ImageUtils.bitmap2Bytes(newBitmap, Bitmap.CompressFormat.JPEG, 100)
        uploadTask1(fileName, file)
        Logger.d("uploadImage fileName=$fileName")
    }

    private fun uploadTask1(fileName: String, file: ByteArray) {
        viewModel.uploadImage(fileName, file)
    }

    private fun getFileNameByUri(uri: Uri): String {
        var fileName = System.currentTimeMillis().toString()
        val cursor = activity!!.contentResolver.query(uri, null, null, null, null)
        if (cursor != null && cursor.count > 0) {
            cursor.moveToFirst()
            fileName =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME))
            cursor.close()
        }
        return fileName
    }


    inner class UploadImageAsyncTask : AsyncTask<Uri, Void?, Void?>() {
        override fun doInBackground(vararg params: Uri): Void? {
            uploadImage1(params[0])
            return null
        }
    }


}